import axios from 'axios';

const API_BASE_URL = 'http://localhost:8080';

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      // 修改 token 格式，确保以 "Bearer " 开头
      config.headers['Authorization'] = `Bearer ${token}`;
      console.log('Request headers:', config.headers);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
api.interceptors.response.use(
  response => {
    console.log('Response received:', {
      url: response.config.url,
      method: response.config.method,
      status: response.status,
      data: response.data
    });

    // 如果是登录响应，保存token和用户信息
    if (response.config.url === '/api/auth/login') {
      console.log('Processing login response:', response.data);
      const { token, user } = response.data;
      console.log('Extracted token and user:', { token: !!token, user });
      
      if (token && user) {
        console.log('Saving token and user data to localStorage');
        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(user));
        
        // 验证数据是否正确保存
        const savedToken = localStorage.getItem('token');
        const savedUser = localStorage.getItem('user');
        console.log('Verified saved data:', {
          tokenSaved: !!savedToken,
          userSaved: !!savedUser,
          savedUserData: JSON.parse(savedUser)
        });
      } else {
        console.error('Token or user data missing in login response:', response.data);
      }
    }
    return response;
  },
  error => {
    console.error('API Error:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      data: error.response?.data
    });

    if (error.response) {
      if (error.response.status === 401) {
        console.log('401 Unauthorized error detected');
        const currentPath = window.location.pathname;
        console.log('Current path:', currentPath);
        
        if (!currentPath.includes('/login')) {
          console.log('Not on login page, clearing auth data and redirecting');
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          window.location.href = '/login';
        } else {
          console.log('Already on login page, skipping redirect');
        }
      }
    }
    return Promise.reject(error);
  }
);

// 认证相关API
export const authAPI = {
  login: async (credentials) => {
    const response = await api.post('/api/auth/login', credentials);
    return response;
  },
  register: (userData) => api.post('/api/users/register', userData)
};

// 用户相关API
export const userAPI = {
  getCurrentUser: () => api.get('/api/users/current'),
  updateProfile: (userData) => api.put('/api/users/profile', userData),
  getAllUsers: () => api.get('/api/users'),
  getUserByUsername: (username) => api.get(`/api/users/${username}`),
  updateUserPermission: (username, permission) => 
    api.put(`/api/users/${username}/permission`, null, { params: { permission } }),
  getUserPermission: (username) => api.get(`/api/users/${username}/permission`),
  hasPermission: (username, permission) => 
    api.get(`/api/users/${username}/has-permission`, { params: { permission } }),
  deleteUser: (username) => api.delete(`/api/users/${username}`)
};

// 订单相关API
export const orderAPI = {
  createOrder: (orderData) => api.post('/api/orders', orderData),
  getOrder: (orderId) => api.get(`/api/orders/${orderId}`),
  getUserOrders: () => api.get('/api/orders/my'),
  updateOrder: (orderId, orderData) => api.put(`/api/orders/${orderId}`, orderData),
  deleteOrder: (orderId) => api.delete(`/api/orders/${orderId}`)
};

export default api;